package com.cskaoyan.shopping.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.form.CartForm;
import com.cskaoyan.shopping.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/shopping")
public class ShoppingCartController {

    @Autowired
    ICartService cartService;

    @GetMapping("carts")
    public ResponseData getCartProducts(HttpServletRequest request) {
        Long userId = parseUserInfo(request);

        CartListByIdRequest cartListByIdRequest = new CartListByIdRequest();
        cartListByIdRequest.setUserId(userId);
        CartListByIdResponse response = cartService.getCartListById(cartListByIdRequest);


        return new ResponseUtil().setData(response.getCartProductDtos());
    }


    @PostMapping("carts")
    public ResponseData postCartProducts(@RequestBody AddCartRequest request) {

        cartService.addToCart(request);

        return new ResponseUtil().setData("成功");
    }

    @PutMapping("carts")
    public ResponseData putCartProducts(@RequestBody UpdateCartNumRequest request){

        cartService.updateCartNum(request);

        return new ResponseUtil().setData("成功");
    }


    private Long parseUserInfo(HttpServletRequest request) {
        String userInfo = request.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long userId = Long.valueOf(object.get("uuid").toString());
        //Integer uId = Long.parseInt(object.get("uuid").toString());
        return userId;
    }
}
